package SingleLinkedList;

public class MySingleLinkedList implements ISingleLinkedList{
    public class ListNode{
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val=val;
        }
    }

    public  ListNode head;

    @Override
    public void display() {
        ListNode cur=head;
        while(cur!=null) {
            System.out.print(cur.val+" ");
            cur=cur.next;
        }
        System.out.println();
    }

    @Override
    public int size() {
        int count=0;
        ListNode cur=head;
        while(cur!=null) {
            count++;
            cur=cur.next;
        }
        return count;
    }

    @Override
    public void addFirst(int val) {
        ListNode node=new ListNode(val);
        if(head==null) {
            head=node;
            return;
        }
        node.next=head;
        head=node;
    }

    @Override
    public void addLast(int val) {
        ListNode node=new ListNode(val);
        if(head==null) {
            head=node;
            return;
        }
        ListNode cur=head;
        while(cur.next!=null) {
            cur=cur.next;
        }
        cur.next=node;
    }

    public ListNode findIndexSubOne(int index) {
        ListNode cur=head;
        for(int i=1;i<=index-1;i++) {
            cur=cur.next;
        }
        return cur;
    }

    @Override
    public void addIndex(int index, int val) {
        ListNode node=new ListNode(val);
        if(index==0) {
            addFirst(val);
            return;
        }
        else if(index==size()){
            addLast(val);
            return;
        }
        ListNode sub=findIndexSubOne(index);
        node.next=sub.next;
        sub.next=node;
    }

    @Override
    public boolean contains(int val) {
        ListNode cur=head;
        while(cur!=null) {
            if(cur.val==val) {
                return true;
            }
            cur=cur.next;
        }
        return false;
    }

    @Override
    public void remove(int val) {
        if(!contains(val)){
            System.out.println("不存在该值");
            return;
        }
        if(head.val==val) {
            head=head.next;
            return;
        }
        ListNode cur=head;
        while(cur.next!=null){
            if(cur.next.val==val) {
                break;
            }
            cur=cur.next;
        }
        cur.next=cur.next.next;
    }

    @Override
    public void removeAllKey(int val) {
        if(head==null) {
            return;
        }
        ListNode prev=head;
        ListNode cur=prev.next;
        while(cur!=null) {
            if(cur.val==val) {
                prev.next=cur.next;
                cur=cur.next;
            }else {
                prev=cur;
                cur=cur.next;
            }
        }
        if(head.val==val) {
            head=head.next;
        }
    }

    @Override
    public void clear() {
        head=null;
    }
}
